package apis

import (
	"github.com/gin-gonic/gin"
	"tylnmall/models"
	"github.com/jinzhu/gorm"
	"common/logger"
	"net/http"
	"tylnmall/constant"
	"errors"
)

func RotationListApi(c *gin.Context){
	var rot []*models.RotationMap
	var err error
	db := c.MustGet("ty").(*gorm.DB)
	if err = db.Find(&rot).Error;err != nil||len(rot) == 0 {
		logger.Error(err)
		err = errors.New("rotation not found")
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	c.JSON(http.StatusOK,gin.H{"rotation":rot})
}

func RotationAddApi(c *gin.Context){
	var rotationmap models.RotationMap
	var err error
	if err = c.Bind(&rotationmap); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	db := c.MustGet("ty").(*gorm.DB)
	if err = db.Create(&rotationmap).Error;err != nil {
		logger.Error(err)
		err = errors.New("create fail")
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	var rots []*models.RotationMap
	if err = db.Find(&rots).Error;err != nil {
		logger.Error(err)
		err = errors.New("db error")
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	c.JSON(http.StatusOK,gin.H{"rotation":rots[len(rots)-1]})
}

func RotationDelApi(c *gin.Context){
	type param struct {
		Id int `json:"id" form:"id"`
	}
	var p param
	var err error
	var rotationmap []models.RotationMap
	if err = c.Bind(&p); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	db := c.MustGet("ty").(*gorm.DB)
	if err = db.Where("id in (?)",p.Id).Delete(&rotationmap).Error;err != nil {
		logger.Error(err)
		err = errors.New("delete fail")
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}

	c.JSON(http.StatusOK,gin.H{"status":"success"})
}
